import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入 store 对象
import store from '@/store'
// 导入组件
import Reg from '@/views/Reg/Reg'
import Login from '@/views/Login/Login'
import Main from '@/views/Main/Main'
import Home from '@/views/Menus/Home/Home'
import UserInfo from '@/views/Menus/User/UserInfo'
import UserAvatar from '@/views/Menus/User/UserAvatar'
import UserPwd from '@/views/Menus/User/UserPwd'
import ArtCate from '@/views/Menus/Article/ArtCate'
import ArtList from '@/views/Menus/Article/ArtList'


// 相当于 将 VueRouter里面的 push 方法进行 重写
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


Vue.use(VueRouter)

const routes = [
  // 配置路由规则对象
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      {
        // 把 一级路由的 / 拼 home  /home
        path: 'home',
        component: Home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫
// to 去哪里
// from 来自哪里
// next 函数 next() 放行 next(false) 阻止 next('路径') 跳转到某个指定页面
router.beforeEach((to, from, next) => {
  const token = store.state.token
  // 如果用户访问的 /login || /reg 直接放行
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    // 如果 访问的不是 这两个路径 需要看看是否有 token 
    if (!token) {
      // 没有token 就跳转到 登录
      next('/login')
    } else {
      next()
    }
  }
  // 如果 没有token  访问的 不是 /login 也不是 /reg 
  // if (!token && to.path !== '/login' && to.path !== '/reg') {
  //   next('/login')
  // } else {
  //   next()
  // }

})


export default router
